import os.path
import json
from pymongo import MongoClient
import requests
from tools.funciton import *
from config.configs import DESKTOP_PATH, DATA_PATH, DOWNLOAD_PATH, ALPHA_DB_PORT, ALPHA_DB_HOST
from time import sleep
from tools.funciton import get_taowu_token

alpha = MongoClient(ALPHA_DB_HOST, ALPHA_DB_PORT).jiwu
header = {
    "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY1MGE0YTg2ODNmOTE1YzM4ZDE4YzY0MCIsImlhdCI6MTcxOTM3MDE1NSwiZXhwIjoxNzE5OTc0OTU1fQ.iAby5Hgy-ib7ZZ2GV0U_hGUNy_Ek6zjuR7Mtqcgfkfw"}


def batch_appointments(merchantCode, warehouseCode):
    """批量创建闪电预约单"""
    file = os.path.join(DOWNLOAD_PATH, '小怪兽.xlsx')
    li, sizes = [], []
    spuIds = read_xlsx_file(file, 0)
    sizes = read_xlsx_file(file, 1)
    nums = read_xlsx_file(file, 2)
    for z in range(len(spuIds)):
        li.append({"barcode": "", "spuId": spuIds[z], "skuId": sizes[z], "appointNum": nums[z]})
    print(json.dumps(li, ensure_ascii=False))
    url = 'https://alpha.geehoop.com/api/backend/storage/appointment/dewu'
    param = {"skuList": li, "campusCode": warehouseCode, "merchantCode": merchantCode, "batchCode": "2023042501",
             "batchCost": 300000,
             "batchMemo": "备注",
             "type": 1}
    response = requests.post(url, headers=header, data=json.dumps(param))
    print(response.text)


batch_appointments()


def batch_create_speed_appointments(merchantCode, batchCode):
    """批量创建极速预约单"""
    url = "https://taowu.geehoop.com/api/backend/storage/appointment"
    dic, dic1 = {}, {}
    token = get_taowu_token()
    print(token)
    arts = read_xlsx_file(os.path.join(DOWNLOAD_PATH, '1216.xlsx'), 1)
    sizes = [int(size) if isinstance(size, float) and size.is_integer() else size for size in
             read_xlsx_file(os.path.join(DOWNLOAD_PATH, '1216.xlsx'), 2)]
    nums = read_xlsx_file(os.path.join(DOWNLOAD_PATH, '1216.xlsx'), 4)
    units = read_xlsx_file(os.path.join(DOWNLOAD_PATH, '1216.xlsx'), 3)
    print(units)

    spus = [articleNumber_to_spuId(str(i)) for i in arts]
    #
    skus = [get_skuId(i, j) for i, j in zip(spus, sizes)]
    param = {"skuList": [], "campusCode": "CKCD01", "merchantCode": merchantCode, "batchCost": 0,
             "batchCode": batchCode}
    for i in range(len(skus)):
        if (spus[i], skus[i]) not in dic:
            dic[(spus[i], skus[i])] = nums[i]
            if isinstance(units[i], int) or isinstance(units[i], float):
                dic1[(spus[i], skus[i])] = units[i]
            else:
                dic1[(spus[i], skus[i])] = 0
        else:
            dic[(spus[i], skus[i])] += nums[i]
    for k, v in dic.items():
        param['skuList'].append(
            {"barCode": "", "spuId": k[0], "skuId": k[1], "appointNum": v, "costUnitPrice": dic1[k]})
    print(param)
    payload = json.dumps(param)
    headers = {
        'authorization': f'Bearer {token}',
        'priority': 'u=1, i',
        'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
        'content-type': 'application/json',
        'Accept': '*/*',
        'Host': 'taowu.geehoop.com',
        'Connection': 'keep-alive'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    print(response.text)


# batch_create_speed_appointments('8646', "2023072401")


def batch_identifying_appointments(appointNos):
    """批量修改极速仓预约单实收数量"""
    for appointNo in appointNos:
        receiptSkuCounts = [i['receiptSkuCounts'] for i in taowu.stock_in_orders.find({"appointNo": appointNo})]
        for item in receiptSkuCounts:
            for spu_id, sku_dict in item.items():
                for sku_id, info in sku_dict.items():
                    info['receiptNum'] = info['appointNum']
        taowu.stock_in_orders.update_one({"appointNo": appointNo}, {"$set": {"receiptSkuCounts": receiptSkuCounts[0]}})


def create_uniqueCode(appointNos):
    """批量创建极速仓预约单唯一码"""
    for appointNo in appointNos:
        url = "https://taowu.geehoop.com/api/backend/stock_in_order/in_stock_order"
        headers = {
            'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY1MGE0YTg2ODNmOTE1YzM4ZDE4YzY0MCIsImlhdCI6MTc0MzA0MDc2NCwiZXhwIjoxNzQzNjQ1NTY0fQ.lgIH50s0TF4IK-C84odI62EMYLWZZF3Y0bHvKWOtN8U'}
        appoint = taowu.stock_in_orders.find_one({"appointNo": appointNo})
        param = {
            "appointNo": appointNo,
            "failSkuCounts": appoint['failSkuCounts'],
            "receiptSkuCounts": appoint['receiptSkuCounts'],
            "otherUnAppointSkuCounts": appoint['otherUnAppointSkuCounts']}
        response = requests.request("POST", url, headers=headers, json=param)
        if response.json()['code'] != 200:
            headers = {'authorization': f'Bearer {get_taowu_token()}'}
            response = requests.request("POST", url, headers=headers, json=param)
            print(response.text)
        print(response.text)
        sleep(1)


def batch_counted_appointments(appointNos):
    """批量完成清点极速仓预约单"""
    for appointNo in appointNos:
        url = f"https://taowu.geehoop.com/api/backend/stock_in_order/counted/{appointNo}"
        headers = {
            'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY1MGE0YTg2ODNmOTE1YzM4ZDE4YzY0MCIsImlhdCI6MTc0MzA0MDc2NCwiZXhwIjoxNzQzNjQ1NTY0fQ.lgIH50s0TF4IK-C84odI62EMYLWZZF3Y0bHvKWOtN8U'}
        response = requests.request("PUT", url, headers=headers)
        if response.json()['code'] != 200:
            headers = {'authorization': f'Bearer {get_taowu_token()}'}
            response = requests.request("PUT", url, headers=headers)
        print(response.text)
        sleep(1)


def batch_identify_appointments(appointNos):
    """批量完成zhijian极速仓预约单"""
    for appointNo in appointNos:
        url = f"https://taowu.geehoop.com/api/backend/stock_in_order/identify/{appointNo}"
        headers = {
            'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY1MGE0YTg2ODNmOTE1YzM4ZDE4YzY0MCIsImlhdCI6MTc0MzA0MDc2NCwiZXhwIjoxNzQzNjQ1NTY0fQ.lgIH50s0TF4IK-C84odI62EMYLWZZF3Y0bHvKWOtN8U'}
        response = requests.request("PUT", url, headers=headers)
        if response.json()['code'] != 200:
            headers = {'authorization': f'Bearer {get_taowu_token()}'}
            response = requests.request("PUT", url, headers=headers)
        print(response.text)
        sleep(1)


def batch_on_shelf_appointments(appointNos, shelfCode):
    """批量上架极速仓预约单"""
    for appointNo in appointNos:
        receiptSkuCounts = [i['receiptSkuCounts'] for i in taowu.stock_in_orders.find({"appointNo": appointNo})]
        print(receiptSkuCounts)
        for item in receiptSkuCounts:
            for spu_id, sku_dict in item.items():
                for sku_id, info in sku_dict.items():
                    info['shelves'] = [
                        {
                            "shelfCode": shelfCode,
                            "qty": info['receiptNum']
                        }
                    ]

        taowu.stock_in_orders.update_one({"appointNo": appointNo}, {"$set": {"receiptSkuCounts": receiptSkuCounts[0]}})


def batch_shelved_appointments(appointNos):
    """批量完成上架极速仓预约单"""
    for appointNo in appointNos:
        url = f"https://taowu.geehoop.com/api/backend/stock_in_order/shelf/{appointNo}"
        headers = {
            'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY1MGE0YTg2ODNmOTE1YzM4ZDE4YzY0MCIsImlhdCI6MTc0MzA0MDc2NCwiZXhwIjoxNzQzNjQ1NTY0fQ.lgIH50s0TF4IK-C84odI62EMYLWZZF3Y0bHvKWOtN8U'}
        response = requests.request("PUT", url, headers=headers)
        if response.json()['code'] != 200:
            headers = {'authorization': f'Bearer {get_taowu_token()}'}
            response = requests.request("PUT", url, headers=headers)
        print(response.text)
        sleep(1)

# batch_on_shelf_appointments(['AP2504159950928'],'TWCDC')
